package com.pets.springboot_petshop.interceptor;

import com.pets.springboot_petshop.util.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@Component
public class Logininterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handle)throws Exception{
        //令牌验证
        String token = request.getHeader("Authorization");
        //验证token
        try {
            Map<String,Object>claims= JwtUtil.parseToken(token);
            //放行
            return true;
        }catch (Exception e){
            response.setStatus(401);
            // 设置响应头为 JSON
            response.setContentType("application/json;charset=utf-8");
            // 写入错误信息
            try (PrintWriter out = response.getWriter()) {
                out.print("{\"status\":\"unauthorized\",\"message\":\"未登录或令牌无效\"}");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            return false;
        }
    }

}
